package com.zhang.webadmin.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhang.webadmin.pojo.AclUser;
import com.zhang.webadmin.pojo.AclUserLoginToken;
import com.zhang.webadmin.service.AclUserLoginTokenService;
import com.zhang.webadmin.service.AclUserService;
import com.zhang.webadmin.util.R;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class LoginTokenFilter extends OncePerRequestFilter {

    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private AclUserLoginTokenService aclUserLoginTokenService;
    @Resource
    private AclUserService aclUserService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf8");
        // 或者根据url去判断处理

        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        AclUserLoginToken aclUserLoginToken = aclUserLoginTokenService.lambdaQuery()
                .eq(AclUserLoginToken::getToken, token)
                .orderByDesc(AclUserLoginToken::getId)
                .last("limit 1")
                .one();
        if (aclUserLoginToken == null) {
            response.getWriter().write(objectMapper.writeValueAsString(R.needLogin("token无效")));
            return;
        }

        AclUser aclUser = aclUserService.getById(aclUserLoginToken.getUid());
        if (aclUser == null) {
            response.getWriter().write(objectMapper.writeValueAsString(R.needLogin("token无效")));
            return;
        }

        UsernamePasswordAuthenticationToken authenticated = UsernamePasswordAuthenticationToken.authenticated(aclUser, null, aclUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticated);

        filterChain.doFilter(request, response);
    }
}
